package net.melon.cata.manager;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import net.melon.cata.manager.exception.OverMaxCountException;
import net.melon.cata.pojo.Catalog;
import net.melon.cata.pojo.CatalogVo;

@Singleton
@Named
public class CatalogManager {

	private CatalogServiceFactory catalogServiceFactory;
	
	public List getChildren(Serializable parentId, Class clazz) {
		CatalogService service;
		try {
			service = getService(clazz);
			return service.getChildren(parentId);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}

	public CatalogVo save(CatalogVo catalog, Class<CatalogVo> clazz)
			throws OverMaxCountException {
		CatalogService service;
		try {
			service = getService(clazz);
			Object o = service.convertFromVo(catalog);
			o =  service.save((Catalog) o);
			catalog = service.convertToVo((Catalog) o);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return catalog;
	}

	public CatalogVo update(CatalogVo catalog, Class<CatalogVo> clazz) {
		CatalogService service;
		try {
			service = getService(clazz);
			Object o = service.convertFromVo(catalog);
			o =  service.update((Catalog) o);
			catalog = service.convertToVo((Catalog) o);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return catalog;
	}

	public void delete(CatalogVo catalog, Class<CatalogVo> clazz) {
		CatalogService service;
		try {
			service = getService(clazz);
			Object o = service.convertFromVo(catalog);
			service.delete((Catalog) o);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public CatalogVo get(Serializable id, Class<CatalogVo> clazz) {
		CatalogService service;
		try {
			service = getService(clazz);
			Object o = service.get(id);
			CatalogVo vo = service.convertToVo((Catalog) o);
			return vo;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	CatalogService getService(Class clazz) throws ClassNotFoundException{
		CatalogService service= catalogServiceFactory.getService(clazz);
		if(service== null){
			throw new ClassNotFoundException("CatalogService named "+clazz.getSimpleName()+Catalog.CATALOG_SERVICE_POSTFIX+" is not found !");
		}
		return service;
	}
	
	@Inject
	public void setCatalogServiceFactory(CatalogServiceFactory catalogServiceFactory) {
		this.catalogServiceFactory = catalogServiceFactory;
	}

}
